import { AnyAction, Reducer } from 'redux';
import { EffectsCommandMap } from 'dva';
import { routerRedux } from 'dva/router';
import { resetPwd, verfiycode } from './service';
import { getPageQuery, setAuthority } from '../login/utils/utils';
import { notification, message } from 'antd';

const R = require('ramda');

export interface StateType {
  status?: 'ok' | 'error';
  currentAuthority?: 'user' | 'guest' | 'admin';
}

export type Effect = (
  action: AnyAction,
  effects: EffectsCommandMap & { select: <T>(func: (state: StateType) => T) => T },
) => void;

export interface ModelType {
  namespace: string;
  state: StateType;
  effects: {
    submit: Effect;
  };
  reducers: {
    registerHandle: Reducer<StateType>;
  };
}

const Model: ModelType = {
  namespace: 'forgotPassword',

  state: {
    status: undefined,
    data: {},
  },

  effects: {
    *resetPwd({ payload }, { call, put }) {
      const response = yield call(resetPwd, { ...R.omit(['onSuccess', 'onFail'])(payload) });
      if (response && response.resultCode === 'ok') {
        message.info('重置密码成功');

        const urlParams = new URL(window.location.href);
        const params = getPageQuery();
        let { redirect } = params as { redirect: string };
        if (redirect) {
          const redirectUrlParams = new URL(redirect);
          if (redirectUrlParams.origin === urlParams.origin) {
            redirect = redirect.substr(urlParams.origin.length);
            if (redirect.match(/^\/.*#/)) {
              redirect = redirect.substr(redirect.indexOf('#') + 1);
            }
          } else {
            window.location.href = redirect;
            return;
          }
        }
        yield put(routerRedux.replace(redirect || '/user/login'));
      } else {
        if (payload.onFail) payload.onFail();
      }
    },

    *verfiycode({ payload }, { call, put }) {
      const response = yield call(verfiycode, { ...R.omit(['onSuccess', 'onFail'])(payload) });
      if (response && response.resultCode === 'ok') {
        if (payload.onSuccess) payload.onSuccess();
      } else {
        if (payload.onFail) payload.onFail();
      }
    },
  },

  reducers: {
    /**
     * 刷新state
     *
     * @param state
     */
    refreshState(state, { payload }) {
      return { ...state, ...payload };
    },
  },
};

export default Model;
